From Command Line - Import CSV file into MongoDB

mongoimport --db airbnb --type csv --file listings_31Mar.csv --headerline -c Rawdata (From Data Preparation Part 1)

mongoimport --db airbnb --type csv --file reviews_27Mar.csv -c reviews (From Data Preparation Part 3)


In [1]:
import pymongo
from pymongo import MongoClient

Connect Python to MongoDB


In [2]:
client = MongoClient('mongodb://localhost:27017/')

Retrieve from Database

Database named as "airbnb"


In [3]:
db = client.airbnb

Retrieve Tables from Database


In [4]:
listings = db.Rawdata
reviews = db.reviews

Store data in a pandas dataframe for further analysis


In [5]:
import pandas as pd

In [6]:
listings_df = pd.DataFrame(list(listings.find()))
reviews_df = pd.DataFrame(list(reviews.find()))

In [7]:
listings_df.head()


Out[7]:
24-hour check-in Air conditioning Breakfast Buzzer/wireless intercom Cable TV Carbon monoxide detector Cat(s) Dog(s) Doorman Dryer ... square_feet state street summary thumbnail_url transit translation missing: en weekly_price xl_picture_url zipcode
0 1 0 1 1 0 0 0 0 0 0 ... Carrer de Sant Josep Oriol, Barcelona, Catalun... Mi casa esta ubicada en el coraz�n de Barcelon... https://a2.muscache.com/im/pictures/34156f3a-4... Todo tipo de transporte: metro, bus, tren, bic... {'hosting_amenity_50': 1, 'hosting_amenity_49'... 0 https://a2.muscache.com/im/pictures/34156f3a-4... 8001
1 0 1 1 1 1 0 0 0 0 0 ... Carrer del Peu de la Creu, Barcelona, Cataloni... The flat is located in Sant Antoni (between Ra... https://a2.muscache.com/im/pictures/826cf18f-6... There is a bike-rental around the corner for d... {'hosting_amenity_50': 1, 'hosting_amenity_49'... 0 https://a2.muscache.com/im/pictures/826cf18f-6... 8001
2 0 0 0 0 0 0 0 0 0 0 ... Carrer del Cid, Barcelona, Catalunya 08001, Spain Located in the Old City, near the famous RAMBL... https://a2.muscache.com/im/pictures/f89056a4-f... Very suitable for tourist visits,example dista... {'hosting_amenity_50': 0, 'hosting_amenity_49'... 0 https://a2.muscache.com/im/pictures/f89056a4-f... 8001
3 0 0 0 0 0 0 0 0 0 0 ... Rambla del Raval, Barcelona, 08001, Spain Double bedroom in the earth of the city, in th... https://a2.muscache.com/im/pictures/d07ab326-0... The flat is near the buses going in few minute... {'hosting_amenity_50': 1, 'hosting_amenity_49'... 0 https://a2.muscache.com/im/pictures/d07ab326-0... 8001
4 0 0 0 0 0 0 0 0 0 0 ... 172 Carrer de la Junta de Comer�, Barcelona, Catal... https://a0.muscache.com/im/pictures/10003580/b... {'hosting_amenity_50': 1, 'hosting_amenity_49'... 0 https://a0.muscache.com/im/pictures/10003580/b... 8001

5 rows × 148 columns


In [8]:
reviews_df.head()


Out[8]:
_id comments date eng_comments id listing_id reviewer_id reviewer_name
0 58ea3c0af5fea093dd7413cc Great apartment with really nice terrace, good... 27/6/2016 Great apartment with really nice terrace, good... 82478807 13343228 13706374 Alessandro
1 58ea3c0af5fea093dd7413cd ?????? ????? ?????????? ? ????????????? ??????... 12/7/2016 The owner is very sympathetic and hospitable p... 85670059 13343228 11822006 ????
2 58ea3c0af5fea093dd7413ce Perfect accomodation for a couple. Everything ... 11/8/2016 Perfect accomodation for a couple. Everything ... 93028358 13343228 78753688 Pasquale
3 58ea3c0af5fea093dd7413cf Logement propre et bien agenc�. La terrasse es... 20/8/2016 Clean and well appointed accommodation. The te... 95694892 13343228 2755964 Matthieu
4 58ea3c0af5fea093dd7413d0 This compact flat is perfect for two persons. ... 27/8/2016 This compact flat is perfect for two persons. ... 97373095 13343228 66079967 Henriett

Sentiment Analysis


In [9]:
from afinn import Afinn
from textblob import TextBlob

1. Calculate AFINN Score


In [10]:
afinn = Afinn()

In [17]:
reviews_df['afinn'] = ""
for i in range(0, len(reviews_df)):
    if pd.isnull(reviews_df.eng_comments[i]):
        reviews_df.loc[i, 'afinn'] = "NA"
    else:
        reviews_df.loc[i, 'afinn'] = afinn.score(reviews_df.loc[i, "eng_comments"])

In [18]:
reviews_df.head(10)


Out[18]:
listing_id id date reviewer_id reviewer_name comments eng_comments afinn
0 13343228 82478807 27/6/2016 13706374 Alessandro Great apartment with really nice terrace, good... Great apartment with really nice terrace, good... 13
1 13343228 85670059 12/7/2016 11822006 ???? ?????? ????? ?????????? ? ????????????? ??????... The owner is very sympathetic and hospitable p... 16
2 13343228 93028358 11/8/2016 78753688 Pasquale Perfect accomodation for a couple. Everything ... Perfect accomodation for a couple. Everything ... 6
3 13343228 95694892 20/8/2016 2755964 Matthieu Logement propre et bien agencé. La terrasse es... Clean and well appointed accommodation. The te... 3
4 13343228 97373095 27/8/2016 66079967 Henriett This compact flat is perfect for two persons. ... This compact flat is perfect for two persons. ... 14
5 13343228 100469165 9/9/2016 44102687 Ewa Apartament by? dobrze usytuowany, kilka minut ... The apartment was well located a few minutes f... 7
6 13343228 111387102 31/10/2016 97786692 (EMAIL HIDDEN) Josep a été très présent dans ses explications... Josep was very present in his explanations to ... 6
7 12941699 76026188 24/5/2016 32294607 Sebastian Excelente anfitrion y apartamento. \r\r\r\nMer... Excellent host and apartment.\r\r\r\r\r\nMerce... 15
8 12941699 78906608 10/6/2016 73370085 Marija This apartment is beautifully decorated, every... This apartment is beautifully decorated, every... 13
9 12941699 79128751 11/6/2016 12294090 James The apartment was in a great location and was ... The apartment was in a great location and was ... 5

2. Split into positive and negative reviews


In [19]:
negative = reviews_df[reviews_df['afinn'] < 0]

In [35]:
positive = reviews_df[reviews_df['afinn'] > 0]

3. Create TFIDF Corpus


In [21]:
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer

In [22]:
hosts = list(listings_df['host_name'])
hosts = [x.lower() for x in hosts if type(x) is str]

In [23]:
stopwords = ['a', 'able', 'about', 'above', 'abroad', 'according', 'accordingly', 'across', 'actually', 'adj', 'after', 'afterwards', 'again', 'against', 'ago', 'ahead', "ain't", 'all', 'allow', 'allows', 'almost', 'alone', 'along', 'alongside', 'already', 'also', 'although', 'always', 'am', 'amid', 'amidst', 'among', 'amongst', 'an', 'and', 'another', 'any', 'anybody', 'anyhow', 'anyone', 'anything', 'anyway', 'anyways', 'anywhere', 'apart', 'appear', 'appreciate', 'appropriate', 'are', "aren't", 'around', 'as', "a's", 'aside', 'ask', 'asking', 'associated', 'at', 'available', 'away', 'awfully', 'b', 'back', 'backward', 'backwards', 'be', 'became', 'because', 'become', 'becomes', 'becoming', 'been', 'before', 'beforehand', 'begin', 'behind', 'being', 'believe', 'below', 'beside', 'besides', 'best', 'better', 'between', 'beyond', 'both', 'brief', 'but', 'by', 'c', 'came', 'can', 'cannot', 'cant', "can't", 'caption', 'cause', 'causes', 'certain', 'certainly', 'changes', 'clearly', "c'mon", 'co', 'co.', 'com', 'come', 'comes', 'concerning', 'consequently', 'consider', 'considering', 'contain', 'containing', 'contains', 'corresponding', 'could', "couldn't", 'course', "c's", 'currently', 'd', 'dare', "daren't", 'definitely', 'described', 'despite', 'did', "didn't", 'different', 'directly', 'do', 'does', "doesn't", 'doing', 'done', "don't", 'down', 'downwards', 'during', 'e', 'each', 'edu', 'eg', 'eight', 'eighty', 'either', 'else', 'elsewhere', 'end', 'ending', 'enough', 'entirely', 'especially', 'et', 'etc', 'even', 'ever', 'evermore', 'every', 'everybody', 'everyone', 'everything', 'everywhere', 'ex', 'exactly', 'example', 'except', 'f', 'fairly', 'farther', 'few', 'fewer', 'fifth', 'first', 'five', 'followed', 'following', 'follows', 'for', 'forever', 'former', 'formerly', 'forth', 'forward', 'found', 'four', 'from', 'further', 'furthermore', 'g', 'get', 'gets', 'getting', 'given', 'gives', 'go', 'goes', 'going', 'gone', 'got', 'gotten', 'greetings', 'h', 'had', "hadn't", 'half', 'happens', 'hardly', 'has', "hasn't", 'have', "haven't", 'having', 'he', "he'd", "he'll", 'hello', 'help', 'hence', 'her', 'here', 'hereafter', 'hereby', 'herein', "here's", 'hereupon', 'hers', 'herself', "he's", 'hi', 'him', 'himself', 'his', 'hither', 'hopefully', 'how', 'howbeit', 'however', 'hundred', 'i', "i'd", 'ie', 'if', 'ignored', "i'll", "i'm", 'immediate', 'in', 'inasmuch', 'inc', 'inc.', 'indeed', 'indicate', 'indicated', 'indicates', 'inner', 'inside', 'insofar', 'instead', 'into', 'inward', 'is', "isn't", 'it', "it'd", "it'll", 'its', "it's", 'itself', "i've", 'j', 'just', 'k', 'keep', 'keeps', 'kept', 'know', 'known', 'knows', 'l', 'last', 'lately', 'later', 'latter', 'latterly', 'least', 'less', 'lest', 'let', "let's", 'like', 'liked', 'likely', 'likewise', 'little', 'look', 'looking', 'looks', 'low', 'lower', 'ltd', 'm', 'made', 'mainly', 'make', 'makes', 'many', 'may', 'maybe', "mayn't", 'me', 'mean', 'meantime', 'meanwhile', 'merely', 'might', "mightn't", 'mine', 'minus', 'miss', 'more', 'moreover', 'most', 'mostly', 'mr', 'mrs', 'much', 'must', "mustn't", 'my', 'myself', 'n', 'name', 'namely', 'nd', 'nearly', 'necessary', 'need', "needn't", 'needs', 'neither', 'never', 'neverf', 'neverless', 'nevertheless', 'next', 'nine', 'ninety', 'no', 'nobody', 'non', 'none', 'nonetheless', 'noone', 'no-one', 'nor', 'normally', 'not', 'nothing', 'notwithstanding', 'novel', 'now', 'nowhere', 'o', 'obviously', 'of', 'off', 'often', 'oh', 'ok', 'okay', 'old', 'on', 'once', 'one', 'ones', "one's", 'only', 'onto', 'opposite', 'or', 'other', 'others', 'otherwise', 'ought', "oughtn't", 'our', 'ours', 'ourselves', 'out', 'outside', 'over', 'overall', 'own', 'p', 'particular', 'particularly', 'past', 'per', 'perhaps', 'placed', 'please', 'plus', 'possible', 'presumably', 'probably', 'provided', 'provides', 'q', 'que', 'quite', 'qv', 'r', 'rather', 'rd', 're', 'really', 'reasonably', 'recent', 'recently', 'regarding', 'regardless', 'regards', 'relatively', 'respectively', 'right', 'round', 's', 'said', 'same', 'saw', 'say', 'saying', 'says', 'second', 'secondly', 'see', 'seeing', 'seem', 'seemed', 'seeming', 'seems', 'seen', 'self', 'selves', 'sensible', 'sent', 'serious', 'seriously', 'seven', 'several', 'shall', "shan't", 'she', "she'd", "she'll", "she's", 'should', "shouldn't", 'since', 'six', 'so', 'some', 'somebody', 'someday', 'somehow', 'someone', 'something', 'sometime', 'sometimes', 'somewhat', 'somewhere', 'soon', 'sorry', 'specified', 'specify', 'specifying', 'still', 'sub', 'such', 'sup', 'sure', 't', 'take', 'taken', 'taking', 'tell', 'tends', 'th', 'than', 'thank', 'thanks', 'thanx', 'that', "that'll", 'thats', "that's", "that've", 'the', 'their', 'theirs', 'them', 'themselves', 'then', 'thence', 'there', 'thereafter', 'thereby', "there'd", 'therefore', 'therein', "there'll", "there're", 'theres', "there's", 'thereupon', "there've", 'these', 'they', "they'd", "they'll", "they're", "they've", 'thing', 'things', 'think', 'third', 'thirty', 'this', 'thorough', 'thoroughly', 'those', 'though', 'three', 'through', 'throughout', 'thru', 'thus', 'till', 'to', 'together', 'too', 'took', 'toward', 'towards', 'tried', 'tries', 'truly', 'try', 'trying', "t's", 'twice', 'two', 'u', 'un', 'under', 'underneath', 'undoing', 'unfortunately', 'unless', 'unlike', 'unlikely', 'until', 'unto', 'up', 'upon', 'upwards', 'us', 'use', 'used', 'useful', 'uses', 'using', 'usually', 'v', 'value', 'various', 'versus', 'very', 'via', 'viz', 'vs', 'w', 'want', 'wants', 'was', "wasn't", 'way', 'we', "we'd", 'welcome', 'well', "we'll", 'went', 'were', "we're", "weren't", "we've", 'what', 'whatever', "what'll", "what's", "what've", 'when', 'whence', 'whenever', 'where', 'whereafter', 'whereas', 'whereby', 'wherein', "where's", 'whereupon', 'wherever', 'whether', 'which', 'whichever', 'while', 'whilst', 'whither', 'who', "who'd", 'whoever', 'whole', "who'll", 'whom', 'whomever', "who's", 'whose', 'why', 'will', 'willing', 'wish', 'with', 'within', 'without', 'wonder', "won't", 'would', "wouldn't", 'x', 'y', 'yes', 'yet', 'you', "you'd", "you'll", 'your', "you're", 'yours', 'yourself', 'yourselves', "you've", 'z', 'zero']
stopwords += ['apartment', 'appartment', 'apartments', 'house', 'room', 'rooms', 'airbnb', 'barcelona', 'accommodation', 'accomodation', 'mention', 'flat', 'review', 'rental', 'brother', 'lover', 'date', 'visit', 'face']
stopwords += hosts

Negative Reviews


In [24]:
vect_neg = TfidfVectorizer(min_df=50, max_df=0.8, token_pattern=r'\b[A-Za-z]{3,}\b', stop_words=stopwords)

In [25]:
X_neg = vect_neg.fit_transform(negative['eng_comments'])
X_df_neg = pd.DataFrame(X_neg.toarray(), index=negative['listing_id'], columns=vect_neg.get_feature_names())

In [26]:
X_df_neg1 = pd.concat([X_df_neg, pd.DataFrame(negative.filter(['listing_id', 'date'])).set_index(negative['listing_id'])], axis = 1, join_axes=[X_df_neg.index])

In [27]:
negative_df = pd.DataFrame(X_df_neg1.set_index(['listing_id', 'date']).stack(), columns = ['tfidf'])
negative_df.index.names = ['listing_id', 'date', 'word']

In [28]:
negative_df = negative_df[negative_df.tfidf != 0]

In [31]:
negative_df.head(20)


Out[31]:
tfidf
listing_id date word
1184282 28/2/2015 bed 0.203680
blocks 0.364102
convenient 0.276450
friends 0.308885
leaving 0.313591
location 0.177114
place 0.194325
recommend 0.235623
stop 0.288096
stops 0.378803
takes 0.379988
walk 0.245436
7722404 3/9/2015 bad 0.192892
bit 0.238298
cockroaches 0.362176
day 0.196549
decided 0.355021
full 0.289345
neighborhood 0.259446
neighbors 0.294312

In [ ]:
#negative_df.to_csv("negative_tfidf.csv")

Positive Reviews


In [36]:
test = positive['eng_comments'][0:50000]

In [32]:
vect_pos = TfidfVectorizer(min_df=50, max_df=0.8, token_pattern=r'\b[A-Za-z]{3,}\b', stop_words=stopwords)

In [37]:
X_pos = vect_pos.fit_transform(positive['eng_comments'])
X_df_pos = pd.DataFrame(X_pos.toarray(), index=positive['listing_id'], columns=vect_pos.get_feature_names())
X_df_pos1 = pd.concat([X_df_pos, pd.DataFrame(positive.filter(['listing_id', 'date'])).set_index(positive['listing_id'])], axis = 1, join_axes=[X_df_pos.index])

In [38]:
positive_df = pd.DataFrame(X_df_pos1.set_index(['listing_id', 'date']).stack(), columns = ['tfidf'])
positive_df.index.names = ['listing_id', 'date', 'word']

In [39]:
positive_df = positive_df[positive_df.tfidf != 0]

In [40]:
positive_df.head(20)


Out[40]:
tfidf
listing_id date word
13343228 27/6/2016 good 0.239664
great 0.200698
helpful 0.289030
metro 0.263450
near 0.382984
position 0.609233
recommend 0.254278
terrace 0.408459
12/7/2016 area 0.139591
balcony 0.181782
bars 0.174421
beautiful 0.153770
calm 0.251774
center 0.161192
city 0.127250
close 0.119401
comfortable 0.241389
compact 0.339195
dinner 0.246993
enjoy 0.203411

In [ ]:
#positive_df.to_csv("positive_tfidf.csv")